package com.vecspace.utils;

import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.NetworkInterface;
import java.net.Socket;
import java.net.SocketException;
import java.util.Enumeration;

public class NetHelper {
	/**
	 * 获取本机的本地ip地址
	 * 地址本地地址分为三段：10.0.0.0 ~ 10.255.255.255、172.16.0.0 ~ 172.31.255.255、192.168.0.0 ~ 192.168.255.255
	 * IPv6的地区本地地址的前12位是FEC，其他的位可以是任意取值，如FED0：：、FEF1：：都是地区本地地址。
	 * 功能描述：
	 * @return
	 * @author: wanghua
	 */
	public static String getLocalIp() {
		Enumeration<NetworkInterface> allNetInterfaces = null;
		try {
			allNetInterfaces = NetworkInterface.getNetworkInterfaces();
		} catch (SocketException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		if(allNetInterfaces == null)return "localhost";
		InetAddress ip = null;
		while (allNetInterfaces.hasMoreElements()) {
			NetworkInterface netInterface = (NetworkInterface) allNetInterfaces.nextElement();
			//System.out.println(netInterface.getName());
			Enumeration<InetAddress> addresses = netInterface.getInetAddresses();
			while (addresses.hasMoreElements()) {
				ip = (InetAddress) addresses.nextElement();
				if (ip != null && ip instanceof Inet4Address && ip.isSiteLocalAddress()) {
					String ipnum = ip.getHostAddress();
					if (!ipnum.equals("127.0.0.1")) {
						return ipnum;
					}
				}
			}
		}
		return "localhost";
	}
	

	
	/**测试端口是否可连通(TCP)
	 * @param hostname
	 * @param port
	 * @return 
	 * @author: wanghua
	 */
	public static boolean tcpping(String hostname, int port) {
		boolean success = false;
		Socket server = null;
		try {
			server = new Socket();
			InetSocketAddress address = new InetSocketAddress(hostname, port);//("192.168.0.201",8899);
			server.connect(address, 3000);
			success = true;
		} catch (Exception e) {
			success = false;//System.out.println("telnet失败");
		}finally{
			if(server!=null){
				try {
					server.close();
				} catch (Exception e) {
				}
			}
		}
		return success;
	}
}
